/*
* Copyright (c)  2017, ueboot.com
* All rights reserved.
* 2017-10-14 21:28:34
*/
package com.ueboot.weishop.admin.controller.goods;

import com.google.common.collect.Lists;
import com.ueboot.core.exception.BusinessException;
import com.ueboot.core.http.response.Response;
import com.ueboot.weishop.admin.controller.goods.vo.*;
import com.ueboot.weishop.entity.activity.ActivityEntity;
import com.ueboot.weishop.entity.goods.*;
import com.ueboot.weishop.entity.setting.AttributeEntity;
import com.ueboot.weishop.entity.setting.BrandEntity;
import com.ueboot.weishop.entity.setting.CategoryEntity;
import com.ueboot.weishop.entity.setting.SpecificationEntity;
import com.ueboot.weishop.service.activity.ActivityService;
import com.ueboot.weishop.service.goods.GoodsInfoService;
import com.ueboot.weishop.service.setting.BrandService;
import com.ueboot.weishop.service.setting.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.Assert;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Id;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by yangkui  on 2017-10-14 21:28:34.
 *
 * @author yangkui
 * @since 2.0 by autocode
 */
@Slf4j
@RestController
@RequestMapping(value = "/goodsInfo")
public class GoodsInfoController {


	@Autowired
	private GoodsInfoService goodsInfoService;


	@Autowired
	private ActivityService activityService;

	@RequiresPermissions("goodsInfo:read")
	@RequestMapping(value = "/page", method = RequestMethod.POST)
	public Response<Page<GoodsInfoResp>> page(@PageableDefault(value = 15, sort = {"id"}, direction = Sort.Direction.DESC)
			                                          Pageable pageable, @RequestBody(required = false) GoodsInfoFindReq req) {
		Page<GoodsInfoEntity> entities = goodsInfoService.findBy(pageable);
		Page<GoodsInfoResp> body = entities.map(entity -> {
			GoodsInfoResp resp = new GoodsInfoResp();
			BeanUtils.copyProperties(entity, resp);
			return resp;
		});

		return new Response<>(body);
	}


	@RequiresPermissions("goodsInfo:read")
	@RequestMapping(value = "/activity/page", method = RequestMethod.POST)
	public Response<Page<GoodsInfoResp>> pageByActivity(@PageableDefault(value = 15, sort = {"id"}, direction = Sort.Direction.DESC)
			                                                    Pageable pageable, @RequestBody(required = false) GoodsInfoFindReq req) {

		log.info("req.getActivityFullPathIds(): {}", req.getActivityFullPathIds());
		if (req.getActivityFullPathIds() == null || req.getActivityFullPathIds().length() <= 0) {
			throw new BusinessException("活动ID参数不存在");
		}
		ActivityEntity activityEntity = this.activityService.get(Long.parseLong(req.getActivityFullPathIds()));
		if (activityEntity == null) {
			throw new BusinessException("该活动不存在");
		}

		Page<GoodsInfoEntity> entities = goodsInfoService.findByActivity(pageable, req.getActivityFullPathIds());
		Page<GoodsInfoResp> body = entities.map(entity -> {
			GoodsInfoResp resp = new GoodsInfoResp();
			BeanUtils.copyProperties(entity, resp);
			return resp;
		});

		return new Response<>(body);
	}


	@RequiresPermissions("goodsInfo:save")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Response<Void> save(@RequestBody GoodsInfoReq req) {
		GoodsInfoEntity entity = null;
		if (req.getId() == null) {
			entity = new GoodsInfoEntity();
		} else {
			entity = goodsInfoService.get(req.getId());
		}
		BeanUtils.copyProperties(req, entity);
		Assert.notNull(req.getCategoryId());
		CategoryEntity category = new CategoryEntity();
		category.setId(req.getCategoryId());
		entity.setCategory(category);
		entity.setCategoryName(req.getCategoryName());
		if (req.getBrandId() != null) {
			BrandEntity brand = new BrandEntity();
			brand.setId(req.getBrandId());
			entity.setBrand(brand);
			entity.setBrandName(req.getBrandName());
		}

		//拼装商品数据和关联数据
		//规格和规格值列表
		List<GoodsSpecValueEntity> goodsSpecValueEntities = this.convert2GoodsSpecValue(entity, req.getGoodsSpecOptions());
		//属性值列表
		List<GoodsAttrEntity> goodsAttrEntities = this.convert2GoodsAttr(entity, req.getGoodsAttrOptions());
		//销售价格列表
		List<GoodsSalesSpecEntity> goodsSalesSpecEntities = this.convert2GoodSalesSpec(entity, req.getGoodsSalesSpecOptions());
		goodsInfoService.saveGoodsInfo(entity, goodsSpecValueEntities, goodsAttrEntities, goodsSalesSpecEntities);
		return new Response<>();
	}

	/**
	 * 将请求对象转换为实体对象
	 * 商品的规格值列表，保存时需要先保存规格，再保存值
	 *
	 * @param goodsSpecOptions
	 * @return
	 */
	private List<GoodsSpecValueEntity> convert2GoodsSpecValue(GoodsInfoEntity goodsInfo, List<GoodsSpecReq> goodsSpecOptions) {
		List<GoodsSpecValueEntity> result = new ArrayList<>();
		if (goodsSpecOptions == null) {
			return result;
		}
		goodsSpecOptions.forEach((spec -> {
			if (spec.getOptions() != null) {
				SpecificationEntity specEntity = new SpecificationEntity();
				specEntity.setId(spec.getSpecId());
				//拼装商品的规格
				GoodsSpecEntity entity = new GoodsSpecEntity();
				entity.setSpec(specEntity);
				entity.setGoodsInfo(goodsInfo);
				//拼装商品的规格值列表
				spec.getOptions().forEach((option) -> {
					GoodsSpecValueEntity specValueEntity = new GoodsSpecValueEntity();
					specValueEntity.setName(option.getName());
					specValueEntity.setValue(option.getValue());
					specValueEntity.setGoodsInfo(goodsInfo);
					specValueEntity.setGoodsSpec(entity);
					result.add(specValueEntity);
				});
			}
		}));

		return result;
	}

	/**
	 * 将请求对象转换为实体对象
	 * 商品的属性列表
	 *
	 * @param goodsAttrOptions
	 * @return
	 */
	private List<GoodsAttrEntity> convert2GoodsAttr(GoodsInfoEntity goodsInfo, List<GoodsAttrReq> goodsAttrOptions) {
		List<GoodsAttrEntity> result = new ArrayList<>();
		if (goodsAttrOptions == null) {
			return result;
		}
		goodsAttrOptions.forEach((option) -> {
			Long attrId = option.getAttrId();
			Assert.notNull(attrId);
			AttributeEntity attributeEntity = new AttributeEntity();
			attributeEntity.setId(attrId);
			GoodsAttrEntity goodsAttrEntity = new GoodsAttrEntity();
			goodsAttrEntity.setAtrValue(option.getAttrValue());
			goodsAttrEntity.setAttrName(option.getAttrName());
			goodsAttrEntity.setGoodsInfo(goodsInfo);
			goodsAttrEntity.setAttr(attributeEntity);
			result.add(goodsAttrEntity);
		});
		return result;
	}

	/**
	 * 将请求对象转换为实体对象
	 * 商品的销售规格列表
	 *
	 * @param goodsSalesSpecOptions
	 * @return
	 */
	private List<GoodsSalesSpecEntity> convert2GoodSalesSpec(GoodsInfoEntity goodsInfo, List<GoodsSalesSpecReq> goodsSalesSpecOptions) {
		List<GoodsSalesSpecEntity> result = new ArrayList<>();
		if (goodsSalesSpecOptions == null) {
			return result;
		}
		goodsSalesSpecOptions.forEach((option) -> {
			GoodsSalesSpecEntity entity = new GoodsSalesSpecEntity();
			Assert.notNull(option.getSpecValueFullPathFieldName());
			Assert.notNull(option.getSpecValueFullPathValue());
			if (!option.getSpecValueFullPathFieldName().endsWith(GoodsSalesSpecEntity.SPLIT_CHAR)) {
				option.setSpecValueFullPathFieldName(option.getSpecValueFullPathFieldName() + GoodsSalesSpecEntity.SPLIT_CHAR);
			}
			if (!option.getSpecValueFullPathValue().endsWith(GoodsSalesSpecEntity.SPLIT_CHAR)) {
				option.setSpecValueFullPathValue(option.getSpecValueFullPathValue() + GoodsSalesSpecEntity.SPLIT_CHAR);
			}
			if (!option.getSpecValueFullPathName().endsWith(GoodsSalesSpecEntity.SPLIT_CHAR)) {
				option.setSpecValueFullPathName(option.getSpecValueFullPathName() + GoodsSalesSpecEntity.SPLIT_CHAR);
			}
			//价格需要*100
			option.setPrice(option.getPrice() * 100);
			BeanUtils.copyProperties(option, entity);
			entity.setGoodsInfo(goodsInfo);
			result.add(entity);
		});
		return result;
	}


	@RequiresPermissions("goodsInfo:delete")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Response<Void> delete(Long[] id) {
		goodsInfoService.delete(id);
		return new Response<>();
	}

	@RequiresPermissions("goodsInfo:delete")
	@RequestMapping(value = "/activity/free", method = RequestMethod.POST)
	public Response<Void> free(@RequestBody List<Integer> reqList) {
		goodsInfoService.deleteGoodsFree(reqList);
		return new Response<>();
	}

	@RequiresPermissions("goodsInfo:delete")
	@RequestMapping(value = "/clearCache", method = RequestMethod.POST)
	public Response<Void> clearCache() {
		goodsInfoService.clearGoodsInfoCache();
		return new Response<>();
	}

	@RequiresPermissions("goodsInfo:read")
	@RequestMapping(value = "/{id}", method = RequestMethod.POST)
	public Response<GoodsInfoResp> get(@PathVariable Long id) {
		GoodsInfoEntity entity = goodsInfoService.get(id);
		GoodsInfoResp resp = new GoodsInfoResp();
		BeanUtils.copyProperties(entity, resp);
		resp.setCategoryId(entity.getCategory().getId());
		return new Response<>(resp);
	}

}
